//
//  WYYXLiveManager.swift
//  liveplugin
//
//  Created by yunxiwangluo on 2020/5/9.
//

import UIKit
import NMCLiveStreaming

//直播的管理类
class WYYXLiveManager {
    
    static let shareInstance = WYYXLiveManager()
    
    var mediaCapture: LSMediaCapture?
    
    var items: [Int32] = [];
    
    //是否开启美颜
    var isFaceU : Bool = false
    
    //初始化capture
    func initMediaCapture(url:String,isVertical:Bool){
        
        initFURenderer()

        //视频配置
        let videoConfig = LSVideoParaCtxConfiguration.defaultVideoConfiguration(LSVideoParamQuality.super_High);
        videoConfig?.interfaceOrientation = isVertical ? LS_CAMERA_ORIENTATION_PORTRAIT : LS_CAMERA_ORIENTATION_RIGHT;
        videoConfig?.cameraPosition = LS_CAMERA_POSITION_FRONT;
        
        //videoConfig?.bitrate = 2000000;

        //音频配置
        let audioConfig = LSAudioParaCtxConfiguration.defaultAudio();

        //总配置
        let config = LSLiveStreamingParaCtxConfiguration.defaultLiveStreaming();
        config?.sLSVideoParaCtx = videoConfig;
        config?.sLSAudioParaCtx = audioConfig

        self.mediaCapture = LSMediaCapture(liveStream: url, withLivestreamParaCtxConfiguration: config);

        var frameID: Int32 = 0;
        
        if let capture = self.mediaCapture{
            
            capture.externalCaptureSampleBufferCallback = { sampleBuffer in
                
                if let sam = sampleBuffer{
                
                    let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sam)!
                
                    if (self.isFaceU){
                    
//                        LivepluginPlugin.renderPixelBuffer(pixelBuffer, withFrameId: frameID, items: &self.items, itemCount: Int32(MemoryLayout.size(ofValue: self.items)))
                        
                        LivepluginPlugin.renderPixelBuffer(pixelBuffer, withFrameId: frameID, items: &self.items, itemCount: Int32(MemoryLayout.size(ofValue: self.items)))

                        frameID = frameID + 1
                    }

                    self.mediaCapture?.externalInputSampleBuffer(sam)
                    
         
                }
            }
            
            LiveEventChannelSupport.sharedInstance.sendCommonDesToFlutter(type: .MSG_INIT_LIVESTREAMING_SUCCESS, des: "初始化直播成功")
            
            //直播中错误监听
            capture.onLiveStreamError = {error in

                if let e = error{
                    print("LM_直播中出现错误：\(e)");
                }
            }

            //直播统计监听
            capture.onStatisticInfoGot = { statistics in

                if let s = statistics{
                    print("LM_直播统计监听：\(s)");
                }

            }
        }else{
            
            print("初始化直播失败");
            LiveEventChannelSupport.sharedInstance.sendCommonDesToFlutter(type: .MSG_INIT_LIVESTREAMING_ERROR, des: "初始化直播出错")
            
        }

    }
    
    func initFURenderer(){
        
//        let v3Path = Bundle.main.path(forResource: "v3", ofType: "bundle")
//
//        FURenderer.share()?.setup(withDataPath: v3Path ?? "", authPackage: &g_auth_package, authSize: Int32(MemoryLayout.size(ofValue: g_auth_package)), shouldCreateContext: true)
        
        let path = Bundle.main.path(forResource: "face_beautification", ofType: "bundle")
        
//        items.append(Int32(FURenderer.item(withContentsOfFile: path ?? "")))
        items.append(Int32(LivepluginPlugin.item(withContentsOfFile: path ?? "")))
        
    }
    

    func setBeauty(whiteColor: Double,redColor: Double,blur: Double,filterName: String,filterValue: Double){
        
        //打开美颜
        isFaceU = true
        
        LivepluginPlugin.itemSetParam(items[0], withName: "color_level", value: whiteColor)
        LivepluginPlugin.itemSetParam(items[0], withName: "red_level", value: redColor)
        LivepluginPlugin.itemSetParam(items[0], withName: "blur_level", value: blur)
        LivepluginPlugin.itemSetParam(items[0], withName: "filter_name", value: filterName)
        LivepluginPlugin.itemSetParam(items[0], withName: "filter_level", value: filterValue)
        
//        FURenderer.itemSetParam(items[0], withName: "color_level", value: whiteColor)
//        FURenderer.itemSetParam(items[0], withName: "red_level", value: redColor)
//        FURenderer.itemSetParam(items[0], withName: "blur_level", value: blur)
//        FURenderer.itemSetParam(items[0], withName: "filter_name", value: filterName)
//        FURenderer.itemSetParam(items[0], withName: "filter_level", value: filterValue)
        
    }
    

    //开始推流
    func startPushStream(call: FlutterMethodCall){

        if let argument = call.arguments{

            let dict:[String:String] = argument as! [String:String];

            let pushUrl = dict["pushUrl"];

            self.mediaCapture?.pushUrl = pushUrl;

            self.mediaCapture?.startLiveStream({ (error) in
                
                if let e = error{
                    print("LM_开始推流失败：\(e)");
                    LiveEventChannelSupport.sharedInstance.sendCommonDesToFlutter(type: .MSG_START_LIVESTREAMING_ERROR, des: "开始推流失败")
                }else{
                    
                    print("LM_开始推流成功");
                    LiveEventChannelSupport.sharedInstance.sendCommonDesToFlutter(type: .MSG_START_LIVESTREAMING_FINISHED, des: "开始推流成功")
                    
                }
                
            })

        }

    }
    
    //结束推流
    func stopPushStream(){
        
        //如果正在直播
        if self.mediaCapture?.checkIsLiving() ?? true{
            
            //停止推流
            self.mediaCapture?.stopLiveStream({ (error) in
                
                if let e = error{
                
                    print("LM_结束推流异常：\(e)")
                    
                    LiveEventChannelSupport.sharedInstance.sendCommonDesToFlutter(type: .MSG_STOP_LIVESTREAMING_ERROR, des: "结束推流失败")
                }else{
                   
                    print("LM_结束推流成功");
                    LiveEventChannelSupport.sharedInstance.sendCommonDesToFlutter(type: .MSG_STOP_LIVESTREAMING_FINISHED, des: "结束推流成功")
                }
                
            })
        }
    }
    

    //开始预览
    func startVideoPreView(preView: UIView,isOpenFace: Bool){

        isFaceU = isOpenFace;
        
//        if isFaceU{
//            FURenderer.itemSetParam(items[0], withName: "filter_name", value: "gexing6")
//            FURenderer.itemSetParam(items[0], withName: "filter_level", value: 1)
//        }
        
        self.mediaCapture?.startVideoPreview(preView)

    }
    
    //释放资源
    func destroy(){
        
        self.mediaCapture?.stopLiveStream({ (error) in
            
            if let e = error{
                
                print("结束直播出错:\(e)")
                
            }else{
                
                
            }
            
            self.mediaCapture?.unInitLiveStream()
            
        })
        
    }
    
    //切换镜像
    func changeOrigation(isVertical: Bool){
        
//        //切换预览镜像
//        self.mediaCapture?.changeIsFrontPreViewMirrored()
        self.mediaCapture?.setBitrate(0, fps: 15, cameraOrientation: isVertical ? LS_CAMERA_ORIENTATION_PORTRAIT : LS_CAMERA_ORIENTATION_RIGHT)
    }
    
    //关闭预览，暂停推流
    func pauseLiveStream(){
        //self.mediaCapture?.pauseVideoLiveStream();
        self.mediaCapture?.pauseVideoPreview();
        self.mediaCapture?.pauseAudioLiveStream();
    }
    
    //打开预览，继续推流
    func rePushLiveStream(){
        self.mediaCapture?.resumeAudioLiveStream();
        self.mediaCapture?.resumeVideoPreview();
        //self.mediaCapture?.resumeVideoLiveStream();
    }
    
    //检测是否正在直播中
    func checkIsLiving() {
        self.mediaCapture?.checkIsLiving();
         LiveEventChannelSupport.sharedInstance.sendCommonDesToFlutter(type: .MSG_STOP_LIVESTREAMING_FINISHED, des: "结束推流成功")
    }
    

    //切换滤镜
    func changeFilter(argument: Dictionary<String,String>?){

        let filterValue = argument?["filterType"];

        var filterType: LSGpuImageFilterType = LS_GPUIMAGE_NORMAL

        switch filterValue {
            case "FilterType.none":
                filterType = LS_GPUIMAGE_NORMAL
                break;
            case "FilterType.clean":
            filterType = LS_GPUIMAGE_MEIYAN1
            break;
            case "FilterType.nature":
            filterType = LS_GPUIMAGE_ZIRAN
            break;
            case "FilterType.whiten":
            filterType = LS_GPUIMAGE_SEPIA
            break;

        default: break

        }

        self.mediaCapture?.setFilterType(filterType);

    }

    //切换前后摄像头
    func switchCamera(){
        self.mediaCapture?.switchCamera({

        })
    }
    //添加水印
    func addWaterMarker(){

    }


}
